$(function(){

    var isload = false;


    /* 时间转化 */
    window.unix_to_datetime = function(unix, isDate) {
        var date = new Date(parseInt(unix) * 1000),
        	m = date.getMonth()+1 >=10? date.getMonth()+1 :'0'+(date.getMonth()+1),
        	d = date.getDate() >=10? date.getDate() :'0'+date.getDate(),
        	h = date.getHours() >=10? date.getHours() :'0'+date.getHours(),
        	min = date.getMinutes() >=10? date.getMinutes() :'0'+date.getMinutes(),
        	s = date.getSeconds() >=10? date.getSeconds() :'0'+date.getSeconds();

        return isDate == undefined ? date.getFullYear()+"-"+ m +"-"+ d +" "+ h +":"+ min +":"+ s : date.getFullYear()+"-"+ m +"-"+ d;
    }

    /* 读取数据 */
    window.lists = function(options){

        if(isload == false){
            var pagelistnum = 10, 
                $tbody = $(options["table"]), 
                $pagenum = $($tbody.attr('pagenum')), 
                $pagination = $($tbody.attr('pagination')); 
            $tbody.html('<div class="preloader-wrapper active table-loading"><div class="spinner-layer spinner-blue-only"><div class="circle-clipper left"><div class="circle"></div></div><div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div>');
            $pagination.html("");
            isload = true;
            $.ajax({
                "url": options["url"],
                "data": options["where"],
                "type": "GET",
                "success": function(data){

                    $.cookie(options["table"], JSON.stringify(options));

                    var list = data["data"],index = data["page"]["nowPage"],count = data["page"]["totalRows"],pagelen = Math.ceil(count/pagelistnum),lidom = '',trdom = '';
          
                    if(list == null || list.length <= 0){
                        trdom += '<div class="nodata"></div>';
                        $tbody.html(trdom);
                        $pagenum.html(0);
                        return false;
                    }else{
                        for(var i = 0; i < list.length; i++){
                            trdom +=  window.bind(list[i], options["table"]);
                        }
                    }
                    $tbody.html(trdom);
                    $pagenum.html(count);

                    if(count > pagelistnum){

                        var i = 0,len = 11;
                        if(pagelen <= 11){
                            i = 1; len = pagelen + 1;
                        }else{
                            if(index <= 6){
                                i = 1; len = 12;
                            }
                            if(index > 6 && index < pagelen - 5){
                                i = index - 5; len = index + 6;
                            }
                            if(index >= pagelen - 5){
                                i = pagelen - 10; len = pagelen+1;
                            }
                        }


                        (pagelen > 11 && index > 6) && $pagination.append('<li class="waves-effect plight pagelink" page="1" table="'+ options["table"] +'"><a>1</a></li>')
                        index != 1 ? $pagination.append('<li class="waves-effect plight pagelink" page="'+ (parseInt(index)-1) +'" table="'+ options["table"] +'"><a><i class="mdi-navigation-chevron-left"></i></a></li>') : $(".pleft").hide();
                        for(; i < len; i++){
                            var style = index == i ? 'active' : 'waves-effect';
                            lidom += '<li class="'+ style +' pagelink" page="'+ i +'" table="'+ options["table"] +'"><a>'+i+'</a></li>';
                        }     
                        $pagination.append(lidom); 
                        index != pagelen ? $pagination.append('<li class="waves-effect pright pagelink" page="'+ (parseInt(index)+1) +'" table="'+ options["table"] +'"><a><i class="mdi-navigation-chevron-right"></i></a></li>') : $(".pright").hide();  
                        (pagelen > 11 && index < pagelen - 5) && $pagination.append('<li class="waves-effect pright pagelink" page="'+ pagelen +'" table="'+ options["table"] +'"><a>'+ pagelen +'</a></li>')            
                    }
                },
                "complete": function(){
                    isload = false; 
                }
            })

        }else{
            alert("正在查询，请稍后~~ (●'◡'●)");
        }
        return false;
    }

    /* 根据条件读取数据 */
    window.listsby = function(options){
    	var data = $.parseJSON($.cookie(options["table"])),
    		url = data.url,
            table = data.table,
    		where = data.where;
    	$.extend(where,options);
    	window.lists({"url": url, "where": where, "table": table});
    }

    var $premodal = $("#premodal");
    $(document).on("keydown", function(e){
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if(e && e.keyCode==13){
            var target = $(document.activeElement);
            if(target.attr("id") == "secrchkey"){
                target.parent("div").prev("button").trigger('click');
            }
        }
    }).on("click", ".pagelink", function(){ //跳转页面
    	var that = $(this),
            data = $.parseJSON($.cookie(that.attr("table"))),
            page = that.attr("page");
    	data.where.page = page;
    	window.lists({ "url": data.url, "where": data.where, "table": data.table});
    }).on("click", ".modal-trigger", function(){  //弹窗操作
        var that = $(this),
            type = that.attr("type"),
            title = that.attr("title"),
            reqlink = that.attr("reqlink"),
            reslink = that.attr("reslink"),
            did = that.attr("did"),
            modal = $(that.attr("href"));
            modal.attr({"type": type,"reslink": reslink, "did": did});

        if(type == "edit"){
            modal.append('<div class="demask"><div class="preloader-wrapper active table-loading"><div class="spinner-layer spinner-blue-only"><div class="circle-clipper left"><div class="circle"></div></div><div class="gap-patch"><div class="circle"></div></div><div class="circle-clipper right"><div class="circle"></div></div></div></div></div>');
            modal.find(".modal-title").html("编辑"+title);
            modal.find(".hideinput").hide();
			var $ipt = modal.find("input,textarea"),
                len = $ipt.length;
            for(var i = 0; i < len; i++){
                if($ipt.eq(i).attr("readonly") != undefined){
                	$ipt.eq(i).parent("div").show();
                }
            }            
            $.get(reqlink, eval('(' + did + ')'), function(data){
                  window.info(data); 
                  modal.find(".demask").fadeOut();   
            })
        }
        if(type == "add"){
            modal.find(".modal-title").html("新增"+title);
            $(".lodebtn").removeAttr('href').css("opacity","0");
            var $ipt = modal.find("input,textarea"),len = $ipt.length, sel = modal.find("select.unupdate"); //不能修改的select
            if(typeof(CKEDITOR) != "undefined"){ CKEDITOR.instances.content.setData('');} 
            sel.removeAttr("disabled"); 
            modal.find(".hideinput").hide();
            for(var i = 0; i < len; i++){
                $ipt.eq(i).val("");
                if($ipt.eq(i).hasClass('unsubmit')){ 
                	$ipt.eq(i).removeAttr("readonly") 
                }
                if($ipt.eq(i).attr("readonly") == "readonly" && !$ipt.eq(i).hasClass('select-dropdown')){
                	$ipt.eq(i).parent("div").hide();
                }
            }
            $("textarea").css("height", "auto")
        }
        if(type == "command"){
        	modal.find(".mtitle").html(title);
        }
        if(type == "changepwd"){
            var cnickname = that.attr("dnickname");
            $("#cpwd").val('');
            $("#cuid").val(did);
            $("#cnickname").val(cnickname);
        }        
        if(type == "check"){
            var fid = that.attr("fid"),name = that.attr("name");
            $("#scomment").val('');
            $("#checkuid").val(did).attr({"fid":fid});
            $("#checknickname").val(name);
        }
        if(type == "comment"){
            var fid = that.attr("fid");
            $("#scomment").val('');
            $("#suid").attr({"fid":fid});
            $("#susername").val('');
        }        
        if(type == "users"){
            var fid = that.attr("fid");
            modal.find(".modal-title").html(title);
            $("#uuid").attr({"fid":fid});
            $("#uusername").val('');
        }
    }).on("click", ".preview", function(){
    	$premodal.html("");
    	var that = $(this),
    		title = that.attr("title"),
    		reslink = that.attr("reslink"),
    		type = that.attr("type");
            desc = that.attr("desc");
    		$premodal.openModal();
    	if(reslink == null){
    		alert("无资源")
    	}else{
	    	switch(type){
	    		case "img":
	    			$premodal.html('<img src="'+ reslink +'" style="width: 100%; display: block; margin: 0 auto" />')
	    			break;
	    		case "audio":
	    			$premodal.html('<p style="width: 500px; margin:30px auto 0 auto;"><a style="color: #999">试听：</a>'+ title +'.mp3</p><audio class="saudio" src="'+ reslink +'"  controls="controls" autoplay="autoplay" style="width: 500px; margin: 10px auto 30px auto; display: block"></audio>')
	    			break;
	    		case "text":
                    $premodal.html('<p style="width: 500px; padding:20px;">' + desc + '</p>');
	    			break;
                case "url":
                    var h = parseInt($(window).height())-280;
                    var sid = that.attr("sid");
                    $premodal.html('<div id="qrcodebg" class="qrcodebg"><div id="sccode"></div></div><iframe id="iframebox" style="height: '+ h +'px;" src="'+ reslink +'"></iframe><div class="modal-tt"><a id="copyurl" url="'+ reslink +'"></a><a href="http://wawa.fm/tv/content.html#'+ sid +'" target="blank"></a><a href="'+ reslink +'" target="blank"></a><a id="rqcode" url="'+ reslink +'"></a></div>').css({"width":"450px","background":"#fff"}).find("iframe").css({"padding":"5px 0 0 0",});
                    $("#copyurl").zclip({
                        path: "../../Public/js/ZeroClipboard.swf",
                        copy: function() {
                            return reslink+"&share=1";
                        },
                        afterCopy: function() {
                            Materialize.toast("已复制链接", 2000);
                        }
                    });
                    $("#sccode").qrcode({
                        render: "canvas",
                        width: 300, //宽度
                        height:300, //高度
                        correctLevel: 1,
                        text: reslink
                    });                    
                                break;                    
                case "apk":
                    $premodal.closeModal();                
                    window.open(reslink);
                    break;                    
	    		default:
	    			break;			
	    	}	
    	}
    }).on("click", "#rqcode", function(){
        $("#qrcodebg").fadeIn();
        return false;
    }).on("click", "#qrcodebg", function(){
        $("#qrcodebg").fadeOut();
        return false;
    }).on("change", ".selectlist", function(){
    	var that = $(this),
    		value = that.find("option:selected").attr("val"),	
    		key = $("#secrchkey").val();
            table = that.attr("table");
    	window.listsby($.extend({"search":key,"table":table},eval('('+ value +')')));
    }).on("click", "#searchlist", function(){
    	var that = $(this),key = that.next("div").find("input").val(),table = that.attr("table");
        window.listsby({"search":key,"table":table,"page":1,"r":10});
    	return false;
    }).on("click", ".orderlist", function(){
		var that = $(this),
            table = that.attr("table"),
    		value = that.attr("value"),
    		sort = that.attr("sort"),
    		list = $.parseJSON($.cookie(table));
        $(".orderby").css("background","#fff");
        that.css("background","#f1f1f1");
        switch(sort){
            case "desc":
                that.attr("sort","asc");
                sort = "asc";
                break;
            case "asc":
                that.attr("sort","desc");
                sort = "desc";
                break;
            default:
                that.attr("sort","desc");
                sort = "desc";                
                break;  
        }    
        window.listsby($.extend({"sort":sort,"table":table}, eval('('+ value +')')));            
    })



    /* 提交数据 */
    window.ajaxsubmit = function(option){

        var modal = $("#"+option["modal"]),tip = modal.find("#help-block"),method = modal.attr("type"),url = modal.attr("reslink");
        tip.html("");
        var $input = $("input[rule],textarea[rule]", modal);
        for(var i = 0; i < $input.length; i++){
            var that = $input.eq(i);
            switch(that.attr("rule")){
                case "password":
                    if(!that.val().match(/^[a-zA-Z0-9]{6,32}$/)){
                        that.focus();
                        tip.html("请填写正确的密码格式：6~16字符，可由字母、数字、或两者组合").fadeIn();
                        return false;                   
                    }
                    break;
                case "username":
                    if(!that.val().match(/^[a-zA-Z0-9_]{2,20}$/)){
                        that.focus();
                        tip.html("请填写正确的昵称格式：2~20字符，可由字母、数字、或两者组合").fadeIn();
                        return false;               
                    }               
                    break;
                case "email":
                    if(!that.focus().val().match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)){
                        that.focus();
                        tip.html("请填写正确的邮箱格式").fadeIn();
                        return false;                           
                    }               
                    break;
                case "tel":
                    if(!that.focus().val().match(/^[0-9-]{4,20}$/)){
                        that.focus();
                        tip.html("请填写正确的电话号码格式").fadeIn();
                        return false;                   
                    }               
                    break;                  
                case "full":
                    if(that.val() == ''){
                        that.focus();
                        tip.html(that.next("label").text()+"不能为空").fadeIn();
                        return false;   
                    }                   
                    break;                      
                default:
                    break;  
            }
        }

        var $subloading = modal.find("#subloading"),
            $subtip = modal.find("#subtip"),
            $tipbg = modal.find("#tipbg"),
            $tiptitle = modal.find("#tiptitle"),
            $tipdesc = modal.find("#tipdesc"),
            $subdemask = modal.find("#subdemask"),
            $subpan = modal.find("#subpan"),
            table = "#tbody";

        $.ajax({
            type: option["type"],
            url: url,
            data: option["data"],
            beforeSend: function(){
                $subdemask.removeClass('hide');
                $subpan.removeClass('hide');
                $tipdesc.html('');
            },
            success: function(data){
                $subloading.addClass("hide");       
                if(data["status"] == 1){
                    $tipbg.attr("class","tipps success-tips").html("<i class='mdi-action-done'></i>");
                    $tiptitle.attr("class","success-a").html("提交完成");
                    $subtip.removeClass('hide');  

                    if(method == "add"){
                        $tipdesc.html("<a id='goon' class='waves-effect waves-light btn tipbtn'>继续添加</a><a id='backlist' class='waves-effect waves-light btn tipbtn'>返回列表</a>");
                    }else{
                        $tipdesc.html("正在关闭窗口");
                        setTimeout(function(){
                            $subdemask.addClass('hide');
                            $subpan.addClass('hide');
                            $closemodal.trigger("click");
                            window.lists($.parseJSON($.cookie(table)));
                        },1000);                        
                    }       
                }else{
                    $tipbg.attr("class","tipps fail-tips").html("<i class='mdi-content-clear'></i>");
                    $tiptitle.attr("class","fail-a").html("未提交")
                    $tipdesc.html(data["info"]+"<br /><br /><a id='reedit' class='waves-effect waves-light btn tipbtn'>重新编辑</a>");
                    $subtip.removeClass('hide');         
                }
            },
            error: function(){
                alert("额，出错了~~  ╮（﹀＿﹀）╭");
                $subdemask.addClass('hide');
                $subpan.addClass('hide');                
                $closemodal.trigger("click");
            },
            complete: function(){
                option["callback"] != undefined && option["callback"]();
            }
        }); 

        return false;
    } 

    /* 上传 */
    $(".fileinput").on("click", function(){
        var that = $(this),
            format = that.attr("format").split("/"),
            filebox = that.parent("div"),
            filetext = filebox.prev(".file-path"),
            loadtip = that.prev("span"),
            pbtn = filebox.next(".handle").find('.lodebtn'), 
            text = loadtip.html();

        if(that.attr("loading") == 1){ 
            alert("正在上传,请稍后"); return false;
        }

        if($(".upload_page",filebox).length == 0){
            var date = Date.parse(new Date());
            var $filedom = $('<div class="uploaddom hide"><iframe id="upload_page'+ date +'" name="upload_page'+ date +'" class="upload_page"></iframe><form class="file_form" action="http://wawa.fm:9090/fileserver/FileServer.php" method="post" enctype="multipart/form-data" target="upload_page'+ date +'"><input class="uploadfile" type="file" name="uploadfile" /></form></div>');
            filebox.append($filedom);  
        }

        var $uploadfile = $(".uploadfile",filebox),
            $file_form = $(".file_form",filebox),
            $upload_page = $(".upload_page",filebox);

        $uploadfile.unbind('change').trigger('click');
        $upload_page.unbind('load');
        $upload_page[0].contentDocument.body.innerHTML = '';

        $uploadfile.on("change", function(){

            var finput = $(this),
                filename = finput.val().replace(/.*(\/|\\)/, ""), 
                fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '',
                isType = false;

            if(finput.val() == ''){ return false;}

            for(var i = 0; i < format.length; i++){
                if(fileExt == format[i]){
                    isType = true;
                }
            }

            if(!isType){
                alert("请上传格式为"+format+"的文件");
                return false;
            }else{
                that.attr("loading","1");
                $file_form.submit();
                loadtip.html("上传中...");
                filebox.css("background","#999");
                $upload_page.load(function() {

                    var $innerhtml = $(this)[0].contentDocument.body.innerHTML;
                    if ($innerhtml != undefined) {

                        res = eval('(' + $innerhtml.substring($innerhtml.indexOf("{"), $innerhtml.lastIndexOf("}") + 1) + ')');
                        if (res.status == 1) {
                            var url = res.url,
	                            preview_url = res.preview_url,
	                            thumbnail = res.thumbnail,
	                            suffix = res.suffix,
	                            time = res.fileinfo && parseInt(res.fileinfo.filetime) * 1000;
                                size = res.fileinfo && parseInt(res.fileinfo.filesize);
                            pbtn.attr({
                                "thumbnail": thumbnail,
                                "href": preview_url
                            }).animate({"opacity":"1"}).find("input").attr({"value":url,"thumbnail": thumbnail, "filetime": time,"filesize": size});
							filebox.css("background","#26a69a");
                            loadtip.html(text);                        
                        }else{
                            alert("上传失败" + res.info);
                        }
                        that.attr("loading","0");
                    }
                })
            }


        })
        return false;
    });


	/* 数据提交弹窗 */
    var $subdemask = $("#subdemask"),
        $subpan = $("#subpan"),
        $infomodal = $("#infomodal"),
        $closemodal = $(".modal-close");

    $("#infomodal").on("click", "#goon", function(){
        var $ipt = $infomodal.find("input"),
            len = $ipt.length;
        for(var i = 0; i < len; i++){
            $ipt.eq(i).val("");
            $ipt.eq(i).removeAttr("val");
        }
        if(typeof(CKEDITOR) != "undefined"){ CKEDITOR.instances.content.setData('');}
        $subdemask.addClass('hide');
        $subpan.addClass('hide');                
        return false;
    }).on("click", "#backlist", function(){
        var table = "#tbody";
        $subdemask.addClass('hide');
        $subpan.addClass('hide');
        $closemodal.trigger("click");
        window.lists($.parseJSON($.cookie(table)));
        return false;
    }).on("click", "#reedit", function(){
        $subdemask.addClass('hide');
        $subpan.addClass('hide');
        return false;
    })    

    /* 表格编辑弹窗 */
	var $editmodal = $("#editmodal"); 

    $editmodal.on("click", "#surebtn", function(){
    	var that = $(this),
            data = eval('(' + $editmodal.attr("did") + ')'),
            table = that.attr("table");
       
    	if($editmodal.attr("type") == "check"){
	    	var $ipts = $("input,textarea",$editmodal);
	    	for(var i = 0,len = $ipts.length; i < len; i++){
	    		if($ipts.val() == ''){
	    			alert("请填写后再提交");
	    			return false;
	    		}
	    	}
    	}

        $editmodal.closeModal();

        $.ajax({
            url: $editmodal.attr("reslink"),
            data: data,
            type: "POST",
            success: function(data){
                Materialize.toast(data["info"], 2000); 
            },
            complete: function(){
                window.lists($.parseJSON($.cookie(table)));
                window.checknum(); 
            }
        })
    	// $.post($editmodal.attr("reslink"), data, function(data){
    	// 	Materialize.toast(data["info"], 2000);  
     //        window.checknum();            
    	// })
    	// window.lists($.parseJSON($.cookie(table)));
    })

    /* 修改密码 */
    var $changepwdmodal = $("#changepwdmodal"); 
    $changepwdmodal.on("click", "#surebtn", function(){
        var cpwd = $("#cpwd"), data = '';
        if(cpwd.val() == ''){ 
            alert("请填写后再提交"); 
            cpwd.focus(); 
            return false;
        }
        data = {"uid": $("#cuid").val(),"password": cpwd.val()}
        $changepwdmodal.closeModal();

        $.post($changepwdmodal.attr("reslink"), data, function(data){
            Materialize.toast(data["info"], 2000);
        })
    })

    /* 审核理由 */
    var $checkmodal = $("#checkmodal"); 
    $checkmodal.on("click", "#surebtn", function(){
        var reason = $("#reason"), data = '',table = $(this).attr("table"),checkuid = $("#checkuid"), fid = checkuid.attr("fid");
        if(reason.val() == ''){ 
            alert("请填写后再提交"); 
            reason.focus(); 
            return false;
        }
        data = $.extend(eval('('+ fid +')'),{"note":reason.val()});
        $checkmodal.closeModal();

        $.ajax({
            url: $checkmodal.attr("reslink"),
            data: data,
            type: "POST",
            success: function(data){
                Materialize.toast(data["info"], 2000); 
            },
            complete: function(){
                window.lists($.parseJSON($.cookie(table)));
                window.checknum(); 
            }
        })
    })

    /* 评论 */
    var $commentmodal = $("#commentmodal"); 
    $commentmodal.on("click", "#surebtn", function(){
        var suid = $("#suid"), data = '',table = $(this).attr("table"),susername = $("#susername"),scomment = $("#scomment"), fid= suid.attr("fid");
        if(scomment.val() == ''){ 
            alert("请填写后再提交"); 
            scomment.focus(); 
            return false;
        }

        data = $.extend(eval('('+ fid +')'),{"from_uid":suid.val(),"content":scomment.val()});
        console.log(JSON.stringify(data));
        $commentmodal.closeModal();

        $.ajax({
            url: $commentmodal.attr("reslink"),
            data: data,
            type: "POST",
            success: function(data){
                Materialize.toast(data["info"], 2000); 
            },
            complete: function(){
                window.lists($.parseJSON($.cookie(table)));
                window.checknum(); 
            }
        })
    })

    /* 评论 */
    var $usersmodal = $("#usersmodal"); 
    $usersmodal.on("click", "#surebtn", function(){
        var uuid = $("#uuid"), data = '',table = $(this).attr("table"),fid= uuid.attr("fid");

        data = $.extend(eval('('+ fid +')'),{"from_uid":uuid.val()});
        console.log(JSON.stringify(data));
        $usersmodal.closeModal();

        $.ajax({
            url: $usersmodal.attr("reslink"),
            data: data,
            type: "POST",
            success: function(data){
                Materialize.toast(data["info"], 2000); 
            },
            complete: function(){
                window.lists($.parseJSON($.cookie(table)));
                window.checknum(); 
            }
        })
    })

})